

//add map area panelId 
var dopBtnorderqueryAdd = "";
var mapManager = null;
var isModify = false;
var isMore = false;
var isSingleUp=false;//是否为单个付款，true为单个，false为批量
var startTime=$("#startTime");
var endTime=$("#endTime");
var loading=$("#loading");//详情loading动画
var detaiTable=$("#dop_datagrid_detail");//详情表格
var detailDiv=$("#detailDiv");//详情div，里面包裹着详情表格
var deliveryManId="";//员工姓名ID，用于查询传值
var returnDate="";//日期，用于查询传值

var total_num, page_size, page_total_num;//总记录数,每页条数,总页数
var page_cur = 1; //当前页

$("#dop_datagrid_query").datagrid({
	url : "",
	height : 600,
	pagination : true,
	fitColumns : false,
	singleSelect : false,
	fit : true,
	pageSize : 1,
	pageList : [ 10, 30, 50, 100 ],
	sortOrder : 'desc',
	rownumbers : true,
	showFooter : true,
	frozenColumns : [ [] ],
	columns : [ [ {
		field : 'ck',
		checkbox : true
	}, {
		field : "deliveryman_id",
		width : 150,
		title : "配送人",
		hidden:true
	}, {
		field : "del_name",
		width : 150,
		title : "员工姓名",
		align:'center'
	}, {
		field : "total",
		width : 150,
		title : "派送数量",
		halign:"center",
		align:'right',
		formatter:function(value, row, index){
			return row.success+row.fail;
		}
	}, {
		field : "success",
		width : 150,
		title : "成功数量",
		halign:"center",
		align:'right'
	}, {
		field : "fail",
		width : 150,
		title : "失败数量",
		halign:"center",
		align:'right'
	}, {
		field : "successRatio",
		width : 150,
		title : "妥投率",
		halign:"center",
		align:'right',
		formatter:function(value,row,index){
			if(row.fail==0){
				return "100.00%";
			}else if(row.success==0){
				return "0.00%";
			}
			var ratio=row.fail/row.success*100;
			return ratio.toFixed(2)+"%";
			
		}
	},  {
		field : "completeTime",
		width : 150,
		title : "订单日期",
		align:'center'
	}, {
		field : "oper",
		width : 150,
		title : "操作",
		align:'center',
		formatter:function(value, row, index){
			/**
			 * 格式化，调用方法显示详情
			 */
			var oper="<a href='javascript:void(0);' onclick='showDetailList(\""+row.deliveryman_id+"\",\""+row.completeTime+"\");'>详情</a>";
			oper+="&nbsp;&nbsp;&nbsp;<a href='javascript:void(0);' onclick='singleUpMoney(\""+row.deliveryman_id+"\",\""+row.completeTime+"\");'>结算</a>";
			return oper;
		}
	} ] ]
});

/**
 * 分页查询详情数据
 * @param {} pageNum
 * @param {} pageSize
 * @param {} deliveryManId，员工姓名ID
 * @param {} returnDate，日期
 */
function getData(pageNum,pageSize,deliveryManId,returnDate) { //获取当前页数据
		loading.nextAll().remove();
        loading.show();
      $.ajax({
          type: 'GET',
          url: 'settleAccoutsController.do?getSettleDetail',
          data: {'pageNum': pageNum - 1,pageSize:pageSize,deliveryManId:deliveryManId,returnDate:returnDate},
          dataType: 'json',
          success: function(data) {
              $("#ul_lists").empty();
              total_num = data.count;//总记录数
              page_size = pageSize;//每页数量
              page_cur = pageNum;//当前页
              page_total_num = data.page_total_num;//总页数，后台生成
              var li = "";
              var list = data.list;
              var dataLength=list.length;
			  var str="";
			  var totalPriceSum=0;
			  var takePriceSum=0;
			  var deliveryPriceSum=0;
			  var upMoneySum=0;
			  //获取数据list
			  var list=data.list;
			  //遍历生成数据追加到表格中
			  for(var i=0;i<dataLength;i++){
					str+="<tr>";
					str+="<td><style='text-align: center;'>"+(i+1)+"</td>";					
					str+="<td><style='text-align: center;'>"+list[i].code+"</td>";					
					str+="<td><style='text-align: center;'>"+list[i].custName+"</td>";					
					str+="<td><style='text-align: center;'>"+list[i].telephone+"</td>";					
					str+="<td><style='text-align: center;'>"+list[i].custAddress+"</td>";					
					str+="<td><style='text-align: center;'>来源"+"</td>";					
					if(list[i].askSendTime==null){
						str+="<td><style='text-align: center;'></td>";	
					}else{
						str+="<td><style='text-align: center;'>"+new Date(list[i].askSendTime).format("yyyy-MM-dd hh:mm")+"</td>";					
					}					
					str+="<td><style='text-align: center;'>"+list[i].deliveryManName+"</td>";					
					str+="<td><style='text-align: center;'>"+list[i].statusText+"</td>";					
					str+="<td><style='text-align: center;'>"+list[i].orderTotalPrice+"</td>";					
					str+="<td><style='text-align: center;'>"+list[i].takeMealPrice+"</td>";					
					str+="<td><style='text-align: center;'>"+list[i].deliveryPrice+"</td>";					
					str+="<td><style='text-align: center;'>"+(list[i].orderTotalPrice-list[i].takeMealPrice)+"</td>";					
					str+="</tr>";	
					if(list[i].status!=6){
						totalPriceSum+=list[i].orderTotalPrice;
						takePriceSum+=list[i].takeMealPrice;
						deliveryPriceSum+=list[i].deliveryPrice;
						upMoneySum+=(list[i].orderTotalPrice-list[i].takeMealPrice);
					}
				}
				str+="<tr>";
				str+="<td><style='text-align: center;'>汇总</td>";					
				str+="<td><style='text-align: center;'></td>";					
				str+="<td><style='text-align: center;'></td>";					
				str+="<td><style='text-align: center;'></td>";					
				str+="<td><style='text-align: center;'></td>";					
				str+="<td><style='text-align: center;'></td>";					
				str+="<td><style='text-align: center;'></td>";					
				str+="<td><style='text-align: center;'></td>";					
				str+="<td><style='text-align: center;'></td>";					
				str+="<td><style='text-align: center;'>"+totalPriceSum+"</td>";					
				str+="<td><style='text-align: center;'>"+takePriceSum+"</td>";					
				str+="<td><style='text-align: center;'>"+deliveryPriceSum+"</td>";					
				str+="<td><style='text-align: center;'>"+upMoneySum+"</td>";					
				str+="</tr>";	
				loading.hide();
				detaiTable.append(str);
          },
          complete: function() {
              getPageBar();//js生成分页
          },
          error: function() {
          }
      });
  }
/**
 * 生成分页按钮
 */
  function getPageBar() { //js生成分页
      if (page_cur > page_total_num)
          page_cur = page_total_num;//当前页大于最大页数
      if (page_cur < 1)
          page_cur = 1;//当前页小于1
      page_str = "<span>共" + total_num + "条</span><span>" + page_cur + "/" + page_total_num + "</span>";
      if (page_cur == 1) {//若是第一页
          page_str += "<span>首页</span><span>上一页</span>";
      } else {
          page_str += "<span><a href='javascript:void(0)' data-page='1'>首页</a></span><span><a href='javascript:void(0)' data-page='" + (page_cur - 1) + "'>上一页</a></span>";
      }
      if (page_cur >= page_total_num) {//若是最后页
          page_str += "<span>下一页</span><span>尾页</span>";
      } else {
          page_str += "<span><a href='javascript:void(0)' data-page='" + (parseInt(page_cur) + 1) + "'>下一页</a></span><span><a href='javascript:void(0)' data-page='" + page_total_num + "'>尾页</a></span>";
      }
      $("#page").html(page_str);
  }

  /**
   * 绑定单击事件
   */
  $("#page a").live('click', function() { //live 向未来的元素添加事件处理器,不可用bind
      var page = $(this).attr("data-page");//获取当前页
      getData(page,5,deliveryManId,returnDate)
  });


/**
 * 通过员工姓名的ID和日期显示详情
 * @param {} manId
 * @param {} date
 */
function showDetailList(manId,date){
	/**
	 * 为员工姓名ID和日期两个全局变量赋值，用于查询
	 */
	deliveryManId=manId;
	returnDate=date;
	/**
	 * 弹出层
	 */
	$.layer({
		type:1,
		title : '<div><span style="padding-left: 14px;line-height: 14px;">详情</span></div>',
		more:true,
		fix:true,
		area : [ 1230, 600 ],
		page : {
			dom : '#detailDiv'
		},
		close:function(index){
			layer.close(index);
			detailDiv.hide();
			loading.nextAll().remove();
		}
	});
	/**
	 * 调用分页方法
	 */
	getData(1,5,deliveryManId,returnDate);
}

//点击查询按钮触发函数
$("#dop_btn_orderquery_query").click(function(){
	queryReturn();
})

function upMoney(deliveryId,completeTime){
	/**
	 * 单个交款
	 */
	var deliveryIds=[];
	var completeTimes=[];
	if(isSingleUp){//单个交款
		layer.confirm("确认要执行此操作吗？",function(index){
			deliveryIds.push(deliveryId);
			completeTimes.push(completeTime);
			EapTools.doAction("settleAccoutsController.do?settleMoney", {deliveryIds:deliveryIds,completeTimes:completeTimes},
			true, function(data) {
				if(data.success){
					layer.close(index);
					EapTip.msgOk("操作成功!");
					queryReturn();
				}
			});
		});
		
	}else{//批量交款
		var select=$("#dop_datagrid_query").datagrid("getSelections");
		if(select.length>0){
			layer.confirm("确认要执行此操作吗？",function(index){
				returnDate=select[0].returnDate;
				for(var i=0;i<select.length;i++){
					deliveryIds.push(select[i].deliveryman_id);
					completeTimes.push(select[i].completeTime);
				}
				EapTools.doAction("settleAccoutsController.do?settleMoney", {deliveryIds:deliveryIds,completeTimes:completeTimes},
				true, function(data) {
					if(data.success){
						layer.close(index);
						EapTip.msgOk("操作成功!");
						queryReturn();
					}
				});
			});
		}else{
			layerComm("请选择要处理的行!","batch_pay");
		}
	}
}

function singleUpMoney(deliveryId,completeTime){
	/**
	 * 单个交款
	 */
	isSingleUp=true;
	upMoney(deliveryId,completeTime);
}

$("#batch_pay").click(function(){
	/**
	 * 批量交款
	 */
	isSingleUp=false;
	upMoney("","");
});
/***
 * layer提示信息封装
 * @param msg  消息内容
 * @param id   要显示位置的元素ID
 */
function layerComm(msg,id){
	layer.tips(msg, document.getElementById(id), {
		guide : 2,
		time : 3,
		more:true
	});
}

// get params
function getQueryParams() {
	return {
		deliveryManId :  $("#deliveryMan").val(),
		startTime : $("#startTime").val(),
		endTime:$("#endTime").val()
	};
}


var p = $("#dop_datagrid_query").datagrid('getPager');
$(p).pagination(
		{
			onSelectPage : function(pageNumber, pageSize) {
				var params = $.extend({
					pageNum : pageNumber,
					pageSize : pageSize
				}, getQueryParams());
				EapTools.doAction("settleAccoutsController.do?queryReturn", params,
						false, function(data) {
							$("#dop_datagrid_query").datagrid('loadData',
									{
										"rows" : data.list,
										"total" : data.count
									} || {});
						});
			}
		});
		
queryReturn();
//查询归班单处理函数
function queryReturn() {
	isMore = true;
	// init
	var options = $("#dop_datagrid_query").datagrid('getPager').data(
			"pagination").options;
	var pageSize = options.pageSize;
	var params = $.extend({
					pageNum : 1,
					pageSize : pageSize
				}, getQueryParams());
	EapTools.doAction("settleAccoutsController.do?queryReturn", params, false,
			function(data) {
				$("#dop_datagrid_query").datagrid('loadData', {
					"rows" : data.list,
					"total" : data.count
					//"footer" : data.footer
				} || {});
			});
	var p = $("#dop_datagrid_query").datagrid('getPager');
	$("td:last", p).find("a").click();
}

/**
 * 格式化日期
 * @param {} fmt
 * @return {}
 */
Date.prototype.Format = function(fmt) 
{ //author: meizz 
  var o = { 
    "M+" : this.getMonth()+1,                 //月份 
    "d+" : this.getDate(),                    //日 
    "h+" : this.getHours(),                   //小时 
    "m+" : this.getMinutes(),                 //分 
    "s+" : this.getSeconds(),                 //秒 
    "q+" : Math.floor((this.getMonth()+3)/3), //季度 
    "S"  : this.getMilliseconds()             //毫秒 
  }; 
  if(/(y+)/.test(fmt)) 
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  for(var k in o) 
    if(new RegExp("("+ k +")").test(fmt)) 
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); 
  return fmt; 
}
		
